// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>Vecen.BangChuang</Solution>
// <Project>Vecen.BangChuang.Core</Project>
// <FileName>LocalFileStorage.cs</FileName>
// <CreateTime>2017-05-06 15:24</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-05-06 15:24" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System;
using System.IO;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.IO.Extensions;
using Abp.Reflection.Extensions;
using Microsoft.Extensions.Configuration;
using Vecen.BangChuang.Configuration;
using Vecen.BangChuang.Web;

namespace Vecen.BangChuang.BangChuang.DomainServices.Common {
    public class LocalFileStorage: IFileStorage, ITransientDependency {
        private readonly string _path;

        public LocalFileStorage() {
            var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
            _path = configuration.GetDownloadPath();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="fileBytes"></param>
        /// <returns></returns>
        public async Task<Guid> SaveFileAsync(byte[] fileBytes) {
            Guid fileName = Guid.NewGuid();
            await Task.Run(() => File.WriteAllBytes(Path.Combine(_path, fileName.ToString()), fileBytes));
            return fileName;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task DeleteFileAsync(Guid fileName) {
            await Task.Run(() => File.Delete(Path.Combine(_path, fileName.ToString())));
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task<byte[]> GetFileAsync(Guid fileName) {
            return await Task.Run(() => {
                using(var stream = File.Open(Path.Combine(_path, fileName.ToString()), FileMode.Open,
                    FileAccess.Read)) {
                    return stream.GetAllBytes();
                }
            });
        }
    }

    public static class ConfigurationExtensions {
        public static string GetDownloadPath(this IConfigurationRoot configuration) {
            var section = configuration.GetSection("FilePath");
            var downloadPath = section["DownloadFilePath"];
            string path = downloadPath;
            if(!Path.IsPathRooted(downloadPath)) {
                path = Path.Combine(WebContentDirectoryFinder.CalculateContentRootFolder(), downloadPath);
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }
    }
}